Skip to main content

Wordfence CLI

** Wordfence CLI – Malware Scanning & WordPress Security Hardening for VPS**

Wordfence CLI is a command-line malware scanner developed by Wordfence. It is designed to protect WordPress sites by scanning files for threats like backdoors, trojans, web shells, and malicious injections. Unlike the Wordfence plugin, Wordfence CLI runs outside WordPress and does not require PHP execution from inside WordPress, making it more secure and performance-friendly for VPS environments.

Purpose and Position in Security Stack

Wordfence CLI is part of Application Layer Security Hardening and works alongside UFW, Fail2Ban, SSH hardening, ModSecurity, and Cloudflare rules.

  • Network layer: UFW, Cloudflare, VPN
  • SSH layer: Key auth, disable root, rate limit
  • IDS layer: Fail2Ban
  • Web Application layer: ModSecurity, WAF
  • Application Anti-Malware layer: Wordfence CLI
  • Backup layer: Rsync, Rclone, snapshots

What You Will Learn

  1. What Wordfence CLI is and when to use it
  2. Installation and environment requirements
  3. Core syntax formula and scan commands
  4. Configuration options and flags
  5. Performance optimization
  6. Malware scan strategies for multi-site VPS
  7. Workflow for automation
  8. Real use cases for malware response
  9. Best practices and limitations
  10. Cheat sheet and mini-quiz

Prerequisites

  • VPS running Ubuntu 20.04/22.04/24.04
  • OpenLiteSpeed stack
  • wp-cli installed
  • Curl + PHP + Zip enabled
  • 64-bit Linux environment
  • Root or sudo access
  • Valid Wordfence CLI API key (Free license OK)

Core Syntax Formula

wordfence verify-key <API_KEY>
wordfence scan <PATH> [OPTIONS]
wordfence version
wordfence help

Installation

5.1 Install Dependencies

sudo apt update
sudo apt install php php-cli php-curl php-zip unzip curl -y

5.2 Download Wordfence CLI

curl -O https://www.wordfence.com/wordfence-cli/wordfence
chmod +x wordfence
sudo mv wordfence /usr/local/bin/

5.3 Verify Installation

wordfence version

Expected output:

Wordfence CLI version X.X.X

5.4 Register License (Free Available)

wordfence verify-key YOUR_API_KEY

Commands and Options Reference

CommandDescription
wordfence scan PATHScan directory for malware
wordfence versionCheck CLI version
wordfence verify-keyActivate license
wordfence helpShow help

Common Options

OptionDescription
--no-scan-pluginsSkip plugins folder
--no-scan-themesSkip themes
--no-scan-coreSkip wp core
--file-scan-sizeLimit scan size
--excludeExclude paths
--outputWrite results to file
--logEnable logging
--timeoutSet scan timeout
--threadsMulti-thread scanning
--memory-limitControl memory usage

Example Scans

7.1 Scan single WordPress site

wordfence scan /home/user/site1/public_html

7.2 Scan all sites on VPS

wordfence scan /home

7.3 Scan with exclusions

wordfence scan /home --exclude=/home/user/backup

7.4 Fast scan mode

wordfence scan /home/user/site1/public_html --no-scan-core --threads=4

Malware Response Workflow

  1. Identify infected files:

    wordfence scan /home/user/site1/public_html --output=malware.txt

  2. Open report:

    cat malware.txt

  3. Backup infected files:

    mkdir infected && cp $(cat malware.txt | awk '{print $1}') infected/

  4. Delete/clean manually

  5. Patch vulnerabilities

  6. Re-scan

Scheduling and Automation

Cron job daily scan:

crontab -e

Add:

0 3 * * * wordfence scan /home --output=/var/log/wf-scan.log

Performance Optimization

OptionPurpose
--threads=4Parallel scanning
--timeout=900Avoid hang
--excludeReduce scan scope
--file-scan-size=10MSpeed scan

Best Practices

  1. Run weekly malware scan
  2. Store logs in /var/log
  3. Combine with UFW + Fail2Ban + Cloudflare
  4. Disable write permissions after deploy
  5. Scan backups before restore
  6. Use .wp-cli config for large sites

Limitations

LimitationDescription
No automatic cleaningManual action required
API key requiredFree plan ok but limited
PHP memory dependentScan may fail low memory
File onlyDoes not scan DB malware

Cheat Sheet

TaskCommand
Verify licensewordfence verify-key KEY
Scan sitewordfence scan /home/site
Fast scanwordfence scan /home --threads=4
Exclude dirs--exclude=/path
Output result--output=malware.txt

Mini Quiz (5 Questions)

  1. What security layer does Wordfence CLI belong to?
  2. Can Wordfence CLI remove malware automatically?
  3. What flag is used to exclude folders?
  4. How to schedule automated scans?
  5. Should you scan backups before restore? Why?

Advanced Configuration

15.1 Set Global Config Directory

Create directory to store logs and configs:

sudo mkdir -p /etc/wordfence-cli
sudo mkdir -p /var/log/wordfence
sudo chown -R $USER:$USER /etc/wordfence-cli /var/log/wordfence

15.2 Configure Runtime Settings

Example config /etc/wordfence-cli/wf.conf:

threads=4
memory_limit=512M
timeout=1200
scan_images=true
scan_archives=true
log=/var/log/wordfence/scan.log

Run using config:

wordfence scan /home --config=/etc/wordfence-cli/wf.conf

Multi-Site Scan Automation (VPS with many WordPress sites)

16.1 Detect all WP installations

find /home -type f -name "wp-config.php"

16.2 Auto Scan All Sites Script

#!/bin/bash
SITES=$(find /home -type f -name "wp-config.php" -printf '%h\n')
for SITE in $SITES; do
echo "Scanning: $SITE"
wordfence scan $SITE --threads=4 --output=$SITE-scan.log
done

Threat Response Playbook

SeverityExample ThreatAction
HighPHP web shell, backdoorQuarantine + root cause check
MediumSuspicious eval() injectionReview + clean
LowModified plugin fileCompare with original version
CriticalMalware persistsFull site isolation

Action Steps (Standard Procedure)

  1. Isolate infection:

    chmod -R 000 /home/user/site1/public_html/wp-content/uploads

  2. Backup infected files:

    tar -czf infected-backup.tar.gz $(cat malware.txt)

  3. Remove malware:

    sed -i '/base64_decode/d' infected-file.php

  4. Patch access:

    • Rotate WP salts
    • Reset SFTP/SSH passwords
    • Change DB user password
  5. Re-scan:

    wordfence scan /home/user/site1/public_html

Integration with UFW + Fail2Ban + Cloudflare

LayerToolPurpose
NetworkUFWBlock unused ports
SSHFail2BanBrute force protection
CDN/WAFCloudflareBlock bad bots
Anti-malwareWordfence CLIDetect file-level threats

Logging and Reporting

19.1 Write logs

wordfence scan /home --log=/var/log/wordfence/scan.log

19.2 View last scan

tail -n 50 /var/log/wordfence/scan.log

19.3 Filter infected files only

grep "MALWARE" /var/log/wordfence/scan.log

Advanced Use Cases

20.1 Scan only changed files in last 48 hours

find /home/user/site1/public_html -type f -mtime -2 -print0 | xargs -0 wordfence scan

20.2 Exclude cache folders

wordfence scan /home --exclude=cache,tmp

20.3 Scan uploaded files only

wordfence scan /home/user/site1/public_html/wp-content/uploads

Security Automation Scripts

21.1 Auto-Isolate Infected Files

wordfence scan /home/user/site1 --output=mal.txt
mkdir quarantine
xargs -a mal.txt -I{} mv {} quarantine/

21.2 Auto Email Report

wordfence scan /home/user/site1 --output=/tmp/scan.log
mail -s "Wordfence Scan Result" admin@example.com &lt; /tmp/scan.log

Incident Response: One-Command Recovery

Clone fresh WP core:

wp core download --force --skip-content

Compare and restore:

diff -r wp-admin/ clean-core/wp-admin/

Best Practices – Strict VPS Policy

  1. Scan uploads daily
  2. Disable write access for wp-config.php
  3. Block php in uploads directory using .htaccess
  4. Block dangerous PHP functions in php.ini
  5. Combine file scan + db scan (search base64, eval)

Real Attack Patterns to Watch

PatternRisk
eval(base64_decodeMalware obfuscation
assert($_POST[Remote code exec
preg_replace /eHidden webshell
.ico PHP payloadHidden malware
random wp-tmp.phpBackdoor dropper

Cheat Sheet – Command Quickfire

TaskCommand
Full scanwordfence scan /home
Fast scan--no-scan-core
Skip plugins--no-scan-plugins
Exclude cache--exclude=cache
Output to file--output=scan.txt

Mini Quiz (Advanced)

  1. How do you schedule VPS-wide scans?
  2. Which flag controls CPU usage?
  3. What is the best folder to quarantine malware?
  4. Why scan uploads separately?
  5. How to detect obfuscated malware?

Enterprise Use Strategy

ScenarioImplementation
Multi-client WordPress serverCentralized scan job + site-level quarantine
High-risk agency environmentUpload scan enforcement
Shared Linux accountsPer-user isolation strategy
Production eCommerce siteIncremental scan strategy + rollback plan

Safe Scan Pipeline (Standard Operating Procedure)

[Scan] → [Verify] → [Quarantine] → [Patch] → [Harden] → [Re-scan] → [Deploy]

Bash Safety Wrappers

29.1 Scan wrapper (safer execution)

#!/bin/bash
TARGET=$1
LOG=/var/log/wordfence/scan-$(date +%F).log
wordfence scan $TARGET --threads=4 --output=$LOG

29.2 Auto block PHP malware inside uploads

find /home -path "*/uploads/*" -name "*.php" -exec mv {} quarantine/ \;

Upload Protection (Zero Malware Upload Policy)

30.1 Real-time enforcement script

Add in cron every 5 minutes:

*/5 * * * * find /home/*/public_html/wp-content/uploads -type f -name "*.php" -delete

30.2 Nginx/OpenLiteSpeed-level hardening

Block PHP inside uploads:

location ~* /wp-content/uploads/.*\.php$ { deny all; }

Defensive Backup Strategy

ProblemRiskSolution
Backups contain malwareReinfectionScan backups weekly
Infection spreads to new serversPersistent malwareScan before restore
Unsafe restoreData lossBackup quarantine

31.1 Scan backup directory

wordfence scan /backup --threads=4

Log Security and Audit Trail

32.1 Log scan history centralized

grep "MALWARE" /var/log/wordfence/*.log

32.2 Track highest risk sites

grep -R "MALWARE FOUND" /var/log/wordfence | cut -d: -f1 | uniq -c | sort -nr

Team Workflow (Agency Model)

RoleResponsibility
Security LeadApproves actions
DevOpsRuns CLI scans
WP EngineerCleans malware
ComplianceKeeps reports

Email and Alert Integration

34.1 Send alert if malware is found

if grep -q "MALWARE" scan.log; then
mail -s "ALERT: Malware Found" admin@example.com &lt; scan.log
fi

Scheduled VPS Protection

ScheduleTask
Dailywp uploads scan
Every 3 dayssystem-wide scan
Weeklyfull malware and signature update
Monthlyretention cleanup

Integration with Rclone + Rsync

Prevent malware inside backups

wordfence scan /backup-before-rclone
rclone copy /backup clean-storage:

CPU & Memory Tuning

FlagUse
--threadsControl CPU
--timeoutPrevent hangs
--memory-limitPrevent OOM kill

Advanced Protection Rules

Detection PatternCommand
Base64 malware searchgrep -R "base64_decode" .
PHP obfuscationgrep -R "eval(" .
Infected backdoor usersgrep -R "wp-create-user" .

Incident Categories

CategoryExampleAction
Red (Critical)active web shellisolate immediately
Yellowobfuscated spam linksclean
Bluemodified plugin filecompare
Greyfalse warningignore

Scan + Clean Automation (Quick)

wordfence scan /home --output=mal.txt
mkdir quarantine
xargs -a mal.txt -I{} mv {} quarantine/

Full Security Pipeline

UFW + Fail2Ban + SSH Hardening

Cloudflare Firewall Rules

ModSecurity WAF

Wordfence CLI File Scan

Backup Integrity Check

Automation + Logs + Alerts

Risk Rating Table

ThreatRisk 1–100Detection by Wordfence CLI
PHP Backdoor95Yes
Malware Upload87Yes
SQL Injection50No
Brute Force30No
XML-RPC attack40No

Final Cheat Sheet

TaskCommand
Full scanwordfence scan /home
Log viewtail -f /var/log/wordfence
Exclude dirs--exclude
Upload cleanfind uploads -name "*.php" -delete

Final Mini Quiz (Advanced)

  1. Why scan backups before restore?
  2. How do you stop PHP execution in uploads?
  3. What does quarantine folder do?
  4. Which threats are NOT detected by Wordfence CLI?
  5. Why combine Wordfence CLI with UFW and Fail2Ban?